import os
import json
from typing import Dict, Any, Tuple, List
from stk_utils import STKUtils,STKObjects

def load_config()->Tuple[Dict[str, any], Dict[str, any]]:
    scenario:Dict[str, any] = {}
    analysis_list:List[str] = []
    """加载配置文件"""
    # 构建文件的绝对路径
    current_file_path  = os.path.abspath(__file__)
    file_path = os.path.join(os.path.dirname(current_file_path), 'config.json')
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        scenario = config.get('scenario', {})
        analysis_list = config.get('analysis_list', [])
        return scenario, analysis_list
    except Exception as e:
        print(f"加载配置文件失败: {str(e)}")
        raise

def create_scenario_inter(config_scenario:Dict[str, any])->Dict[str, any]:
    '''
    details: 创建场景,返回scenario中IAgStkObject对象集合
    return: obj_dic
    '''
    try:
        # 初始化STK工具
        scenario_name = config_scenario.get('scenario_name')
        stk = STKUtils(scenario_name)
        obj_dic:Dict[str, any] = {}  # 初始化 obj_dic
        # 创建场景对象
        for obj in config_scenario['objects']:
            obj_name = obj['name']
            print(f"正在创建对象: {obj_name}")
            
            # 创建主对象
            obj_config = next(
                (o for o in config_scenario['objects'] if o['name'] == obj_name),
                None
            )
            if not obj_config:
                raise Exception(f"未找到对象配置: {obj_name}")
            
            stk_obj = stk.create_object(obj_config)
            if stk_obj is None:
                raise Exception(f"对象创建失败: {obj_name}")
            # 添加到obj字典
            obj_dic[obj_name] = stk_obj.QueryInterface(STKObjects.IAgStkObject)
            # 创建附加对象
            if 'attached_objects' in obj_config:
                for attached_obj in obj_config['attached_objects']:
                    if not stk.add_sensor(obj_name, attached_obj):
                        raise Exception(f"附加对象创建失败: {attached_obj['name']}")
                    obj_dic[attached_obj['name']] = obj_dic[obj_name].Children.Item(attached_obj['name'])
        
        # 保存场景
        # save_file = os.path.join(os.getcwd(), config_scenario.get("path"), f"{scenario_name}.sc")
        # if not stk.save_scenario(save_file):
        #     raise Exception("场景保存失败")
        return obj_dic
    
    except Exception as e:
        print(f"场景创建失败：{str(e)}")
        raise

def exec_task_inter(analysis_list:Dict[str, any], obj_dic:Dict[str, any])->Dict[str, any]:
    #calc access bt SAR and ship 
    for task in analysis_list:
        if task['analysis_type'] == 'Access':
            observed, observer = obj_dic[task['parameters']['observed']], obj_dic[task['parameters']['observer']]
            
            access = observed.GetAccessToObject(observer)
            access.ComputeAccess()# 获取访问结果
            access_intervals = access.ComputedAccessIntervalTimes
            res:Dict[str, any] = {}
            # 打印访问结果
            for i in range(access_intervals.Count):
                interval = access_intervals.GetInterval(i)
                start_time = interval[0]
                stop_time = interval[1]
                # print(f"访问开始时间: {start_time}, 访问结束时间: {stop_time}")
                # 将访问时间存储到字典中
                res[f"Access_{i}"] = {"开始时间": start_time, "结束时间": stop_time}
            return res

if __name__ == '__main__':
    scenario, analysis_list = load_config()
    # step1 create_scenario from config
    obj_dic = create_scenario_inter(scenario)
    print(obj_dic)
    # step2 analyze task from config
    res = exec_task_inter(analysis_list, obj_dic)
    print(res)
